<template>
  <div class="fill-blank-container">
    <!-- 页面头部 -->
    <header class="page-header">
      <div class="quiz-stats">
        <span>总题数: 20 题</span>
        <span class="separator">|</span>
        <span>已完成: {{ completedCount }} 题</span>
        <span v-if="isSubmitted" class="separator">|</span>
        <span v-if="isSubmitted" class="score">得分: {{ score }} / 100</span>
      </div>
    </header>

    <!-- 题目区域 -->
    <main class="questions-container">
      <div 
        v-for="(question, index) in questions" 
        :key="index" 
        class="question-card"
        :class="{
          'completed': question.userAnswer.trim() !== '',
          'correct': isSubmitted && isAnswerCorrect(question),
          'incorrect': isSubmitted && question.userAnswer.trim() !== '' && !isAnswerCorrect(question)
        }"
      >
        <div class="question-number">题目 {{ index + 1 }}:</div>
        
        <div class="question-content">
          <p class="question-sentence">
            <template v-for="(part, partIdx) in question.sentenceParts" :key="partIdx">
              <!-- 文本部分 -->
              <span v-if="typeof part === 'string'" class="sentence-text">{{ part }}</span>
              
              <!-- 填空部分 -->
              <span v-else class="blank-wrapper">
                <input
                  type="text"
                  ref="inputRefs"
                  v-model="question.userAnswer"
                  :placeholder="part.hint || '请输入答案'"
                  :disabled="isSubmitted"
                  class="blank-input"
                  @keyup.enter="handleEnter(index + 1)"
                  @input="handleInput(index)"
                >
                <!-- 正确答案（提交后显示） -->
                <span v-if="isSubmitted && !isAnswerCorrect(question)" class="correct-answer">
                  正确答案: {{ question.correctAnswer }}
                </span>
              </span>
            </template>
          </p>
          
          <!-- 解析（提交后显示） -->
          <div v-if="isSubmitted" class="explanation">
            <strong>解析：</strong>{{ question.explanation }}
          </div>
        </div>
      </div>
    </main>

    <!-- 控制按钮 -->
    <div class="control-buttons">
      <button 
        @click="handleSubmit" 
        class="submit-btn"
        :disabled="isSubmitted || completedCount < 3"
      >
        提交答案
      </button>
      
      <button 
        @click="handleReset" 
        class="reset-btn"
      >
        重新开始
      </button>
      
      <button 
        @click="scrollToTop" 
        class="top-btn"
        :class="{ 'visible': showScrollTop }"
      >
        回到顶部
      </button>
    </div>
  </div>
</template>

<script setup>
import {ref, computed, onMounted, onUnmounted, getCurrentInstance} from 'vue';
import {shuffleArray} from "@/api/utils/index.js";

// 存储输入框refs，格式: { [field]: { [id]: 输入框DOM } }
const inputRefs = ref([]);

// 20道英语填空题数据
const questions = ref([
  {
    sentenceParts: [
      "She ", 
      { hint: "动词，第三人称单数" }, 
      " to school every day."
    ],
    correctAnswer: "goes",
    explanation: "主语是第三人称单数 She，一般现在时动词后加 s。",
    userAnswer: ""
  },
  {
    sentenceParts: [
      "I ", 
      { hint: "助动词，第一人称" }, 
      " reading a book now."
    ],
    correctAnswer: "am",
    explanation: "now 表示现在进行时，第一人称后用 am。",
    userAnswer: ""
  },
  {
    sentenceParts: [
      "He ", 
      { hint: "动词过去式" }, 
      " to the park yesterday."
    ],
    correctAnswer: "went",
    explanation: "yesterday 表示过去时，go 的过去式是 went。",
    userAnswer: ""
  },
  {
    sentenceParts: [
      "We have ", 
      { hint: "动词过去分词" }, 
      " this movie before."
    ],
    correctAnswer: "seen",
    explanation: "have + 过去分词构成现在完成时，see 的过去分词是 seen。",
    userAnswer: ""
  },
  {
    sentenceParts: [
      "There are ", 
      { hint: "数量词(许多)" },
      " books on the table."
    ],
    correctAnswer: "many",
    explanation: "books 是可数名词复数，用 many 修饰。",
    userAnswer: ""
  },
  {
    sentenceParts: [
      "This is ", 
      { hint: "物主代词(第一人称)" },
      " pen."
    ],
    correctAnswer: "my",
    explanation: "形容词性物主代词 my 修饰名词 pen。",
    userAnswer: ""
  },
  {
    sentenceParts: [
      "He can ", 
      { hint: "动词原形" }, 
      " English well."
    ],
    correctAnswer: "speak",
    explanation: "情态动词 can 后接动词原形。",
    userAnswer: ""
  },
  {
    sentenceParts: [
      "They ", 
      { hint: "助动词，复数" }, 
      " playing football now."
    ],
    correctAnswer: "are",
    explanation: "now 表示现在进行时，复数主语后用 are。",
    userAnswer: ""
  },
  {
    sentenceParts: [
      "She is ", 
      { hint: "形容词比较级(tall)" },
      " than her sister."
    ],
    correctAnswer: "taller",
    explanation: "than 是比较级的标志，tall 的比较级是 taller。",
    userAnswer: ""
  },
  {
    sentenceParts: [
      "I will ", 
      { hint: "动词原形" }, 
      " my homework tonight."
    ],
    correctAnswer: "do",
    explanation: "will 后接动词原形构成一般将来时。",
    userAnswer: ""
  },
  {
    sentenceParts: [
      "This is the ", 
      { hint: "形容词最高级(好)" },
      " book I have ever read."
    ],
    correctAnswer: "best",
    explanation: "最高级前通常加 the，good 的最高级是 best。",
    userAnswer: ""
  },
  {
    sentenceParts: [
      "He has been living here ", 
      { hint: "介词" }, 
      " 2010."
    ],
    correctAnswer: "since",
    explanation: "since 后接时间点，表示从过去某时一直持续到现在。",
    userAnswer: ""
  },
  {
    sentenceParts: [
      "She didn't ", 
      { hint: "动词原形" }, 
      " to the party last night."
    ],
    correctAnswer: "go",
    explanation: "助动词 didn't 后接动词原形。",
    userAnswer: ""
  },
  {
    sentenceParts: [
      "If it rains tomorrow, we ", 
      { hint: "将来时动词" }, 
      " stay at home."
    ],
    correctAnswer: "will",
    explanation: "if 引导的条件状语从句用一般现在时，主句用一般将来时。",
    userAnswer: ""
  },
  {
    sentenceParts: [
      "There is ", 
      { hint: "数量词" }, 
      " water in the glass."
    ],
    correctAnswer: "some",
    explanation: "water 是不可数名词，肯定句中用 some 修饰。",
    userAnswer: ""
  },
  {
    sentenceParts: [
      "He is interested ", 
      { hint: "介词" }, 
      " playing basketball."
    ],
    correctAnswer: "in",
    explanation: "be interested in 是固定搭配，表示对...感兴趣。",
    userAnswer: ""
  },
  {
    sentenceParts: [
      "We should ", 
      { hint: "动词原形" }, 
      " attention to our health."
    ],
    correctAnswer: "pay",
    explanation: "should 后接动词原形，pay attention to 是固定短语。",
    userAnswer: ""
  },
  {
    sentenceParts: [
      "This book ", 
      { hint: "动词被动语态" }, 
      " written by him last year."
    ],
    correctAnswer: "was",
    explanation: "被动语态结构为 be + 过去分词，过去时单数用 was。",
    userAnswer: ""
  },
  {
    sentenceParts: [
      "I have been waiting ", 
      { hint: "介词" }, 
      " two hours."
    ],
    correctAnswer: "for",
    explanation: "for 后接时间段，表示持续了多长时间。",
    userAnswer: ""
  },
  {
    sentenceParts: [
      "She asked me ", 
      { hint: "连词" }, 
      " I could help her."
    ],
    correctAnswer: "if",
    explanation: "if 在这里引导宾语从句，表示是否的意思。",
    userAnswer: ""
  }
]);

// 状态管理
const isSubmitted = ref(false);
const showScrollTop = ref(false);

const {proxy} = getCurrentInstance();

// 计算已完成题目数量
const completedCount = computed(() => {
  return questions.value.filter(q => q.userAnswer.trim() !== '').length;
});

// 检查答案是否正确（忽略大小写）
const isAnswerCorrect = (question) => {
  return question.userAnswer.trim().toLowerCase() === question.correctAnswer.toLowerCase();
};

// 计算得分
const score = computed(() => {
  const correctCount = questions.value.filter(q => isAnswerCorrect(q)).length;
  return Math.round((correctCount / questions.value.length) * 100);
});

// 处理输入事件
const handleInput = (index) => {
  // 可以在这里添加输入验证逻辑
};

// 提交答案
const handleSubmit = () => {
  isSubmitted.value = true;
};

// 重置答题
const handleReset = () => {
  questions.value = shuffleArray(questions.value);
  questions.value.forEach(q => {
    q.userAnswer = "";
  });
  isSubmitted.value = false;
  scrollToTop();
};

// 回到顶部
const scrollToTop = () => {
  window.scrollTo({
    top: 0,
    behavior: 'smooth'
  });
};

// 监听滚动事件，控制回到顶部按钮显示
const handleScroll = () => {
  showScrollTop.value = window.scrollY > 300;
};

// 挂载和卸载滚动事件监听
onMounted(() => {
  questions.value = shuffleArray(questions.value);
  window.addEventListener('scroll', handleScroll);
});

onUnmounted(() => {
  window.removeEventListener('scroll', handleScroll);
});

// 处理回车事件
const handleEnter = (currentId) => {
  // 检查下一行是否存在
  if (currentId < questions.value.length) {
    // const nextRow = questions.value[nextIndex];
    const nextInput = inputRefs.value[currentId];
    // console.log(nextInput);
    if (nextInput) {
      nextInput.focus();
    }
  } else {
    // 如果是最后一行，可选择聚焦到第一行或其他处理
    proxy.$modal.msgWarning("已到达最后一行")
  }
};
</script>

<style scoped>
.fill-blank-container {
  max-width: 900px;
  margin: 0 auto;
  padding: 20px;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  color: #333;
  line-height: 1.8;
}

/* 头部样式 */
.page-header {
  padding: 20px;
  color: black;
  border-radius: 8px;
  margin-bottom: 30px;
}

.page-header h1 {
  margin: 0 0 15px 0;
  font-weight: 600;
}

.quiz-stats {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  font-size: 14px;
}

.separator {
  color: #bbb;
}

.score {
  color: #4cd964;
  font-weight: 500;
}

/* 题目容器样式 */
.questions-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.question-card {
  background-color: #fff;
  border: solid 1px #ddd;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.question-card.completed {
  border-left: 4px solid #3498db;
}

.question-card.correct {
  border-left: 4px solid #2ecc71;
  background-color: #f8fffa;
}

.question-card.incorrect {
  border-left: 4px solid #e74c3c;
  background-color: #fff5f5;
}

.question-number {
  font-weight: bold;
  color: #2c3e50;
  margin-bottom: 10px;
  font-size: 16px;
}

.question-sentence {
  margin: 0;
  font-size: 18px;
  line-height: 1.8;
}

.sentence-text {
  white-space: pre-wrap;
}

.blank-wrapper {
  position: relative;
  margin: 0 8px;
}

.blank-input {
  width: 300px;
  padding: 8px 12px;
  border: 2px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  text-align: center;
  transition: all 0.2s;
}

.blank-input:focus {
  outline: none;
  border-color: #3498db;
  box-shadow: 0 0 0 2px rgba(52, 152, 219, 0.2);
}

.blank-input:disabled {
  background-color: #f5f5f5;
  cursor: not-allowed;
}

.correct-answer {
  display: block;
  margin-top: 5px;
  font-size: 14px;
  color: #e74c3c;
  font-style: italic;
}

.explanation {
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px dashed #e1e4e8;
  font-size: 15px;
  color: #495057;
}

/* 按钮样式 */
.control-buttons {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin: 40px 0 60px 0;
  position: relative;
}

.submit-btn, .reset-btn {
  padding: 12px 30px;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.25s ease;
}

.submit-btn {
  background-color: #3498db;
  color: white;
}

.submit-btn:hover:not(:disabled) {
  background-color: #2980b9;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(52, 152, 219, 0.3);
}

.submit-btn:disabled {
  background-color: #a0c4e7;
  cursor: not-allowed;
}

.reset-btn {
  background-color: #f1f3f5;
  color: #495057;
}

.reset-btn:hover {
  background-color: #e9ecef;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.top-btn {
  position: fixed;
  bottom: 30px;
  right: 30px;
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background-color: #3498db;
  color: white;
  border: none;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
  transition: all 0.3s ease;
  opacity: 0;
  visibility: hidden;
}

.top-btn.visible {
  opacity: 1;
  visibility: visible;
}

.top-btn:hover {
  background-color: #2980b9;
  transform: translateY(-3px);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .question-sentence {
    font-size: 16px;
  }
  
  .blank-input {
    width: 120px;
  }
  
  .control-buttons {
    flex-direction: column;
    align-items: center;
  }
  
  .submit-btn, .reset-btn {
    width: 100%;
    max-width: 300px;
  }
}
</style>
